#盘中实时
import json
import pathlib
import time
import re
import os
import psutil
import pyttsx3
import requests
import pyperclip
import pyautogui
import win32api
from PySide6 import QtGui
from PySide6.QtWidgets import QApplication,QMainWindow,QTableWidgetItem,QHeaderView,QAbstractItemView,QTableWidget,QLabel,QHBoxLayout,QPushButton,QVBoxLayout,QMenu
from PySide6.QtCore import Qt, QDate, Slot, QUrl, QObject, Signal
from PySide6.QtGui import QFont,QColor,QPalette,QBrush,QAction,QCursor

from ui.simplekanpan import Ui_mainWindow
from api.thsApi.testThs import send_code_message
from api.thsApi.beizhutest import movedate
from apscheduler.schedulers.background import BackgroundScheduler
from datetime import datetime
from PySide6.QtWebEngineWidgets import QWebEngineView


import config.globalVariable as Gv
import api.kaipanla.KaiPanLaAPI as kplAPI
import api.xuangubaoApi.XgbApi as xgbAPI
import api.xuangubaoApi.XgbWebSocketMsg as xgbwebMsg
import api.dfcfApi.DfcfApi as dfcfAPI
import page.MarketSentiment as mark
import page.common.HttpClientResp as httpResp
import api.thsApi.test as test
import api.thsApi.beizhutest as bz
import api.thsApi.LhbSearchApi as lhb
import page.dayexpect as de
import page.platePop as platepop

# 创建一个调度器
scheduler = BackgroundScheduler()
jobMap = {}
table_widgets_new = []
table_widgets_sub_new = []
table_widgets_label_new = []
button_zpjjz = []
button_zpjjz_lb = []
#备注坐标
bz_location = []
#当前日期或者上一个交易日日期
current_time = datetime.now().strftime('%Y-%m-%d')
#每日复盘显示时间
mrfp_show_time = None
num = 10
days = None
hreaddata = {}
openstatus = 1
port_global = 8001

class MyData:
    def __init__(self, value):
        self.value = value

class MyObject(QObject):
    # 定义一个带有参数的信号
    mySignal = Signal(MyData)

    def triggerSignal(self, data):
        # 触发信号，并传递参数
        self.mySignal.emit(data)
class MainUI(QMainWindow,Ui_mainWindow):
    def __init__(self,parent=None):
        super(MainUI,self).__init__(parent)
        self.setupUi(self)
        #设置表格样式
        self.settableStyle(self.tableWidget_pzbkrq,1)
        self.settableStyle(self.tableWidget_pzbkxgg, 0)
        self.tableWidget_pzbkxgg.setAccessibleName(Gv.BKXGG)
        self.settableStyle(self.tableWidget_lhb_table, 0)
        self.tableWidget_lhb_table.setAccessibleName(Gv.LHB)
        #self.settableStyle(self.tableWidget__yqset, 0)
        self.tableWidget__yqset.setAccessibleName(Gv.YQSZ)
        #设置表格选中
        self.tableWidget_pzbkrq.clicked.connect(self.onRowClicked)
        self.tableWidget_pzbkxgg.clicked.connect(self.onRowPzbkxggClicked)
        #定时选中
        self.comboBox.currentIndexChanged.connect(self.onComboboxBkSelect)
        self.comboBox.setAccessibleName(Gv.PZBK)
        self.comboBox_2.currentIndexChanged.connect(self.onComboboxBkGGSelect)
        self.comboBox_2.setAccessibleName(Gv.PZBKXGG)
        self.checkBox_zdsx.stateChanged.connect(self.onCheckBoxStateChanged)
        #tab切换
        self.tabWidget.currentChanged.connect(self.onTabChanged)
        #每日复盘
        self.settableStyle(self.tableWidget, 0)
        self.tableWidget.setAccessibleName(Gv.MRFP)
        self.checkBox_delSt.stateChanged.connect(self.onCheckBoxStateChanged_mrfp_delst)

        width = self.groupBox_17.width() / num

        height_label = self.groupBox_16.height()
        labeList = [QLabel(self) for _ in range(num)]
        layout_label = QHBoxLayout()
        layout_label.setDirection(QHBoxLayout.RightToLeft)
        self.groupBox_16.setLayout(layout_label)
        for i, label in enumerate(labeList):
            name = Gv.TABBKLABEL + '_' + str(i)
            label.setAccessibleName(name)
            label.setObjectName(name)
            label.setFixedWidth(width-2)
            label.setFixedHeight(height_label-5)
            table_widgets_label_new.append(name)
            layout_label.addWidget(label)

        height = self.groupBox_17.height()

        layout = QHBoxLayout()
        layout.setDirection(QHBoxLayout.RightToLeft)
        self.groupBox_17.setLayout(layout)
        # 创建10个QTableWidget
        table_widgetslist = [QTableWidget(self) for _ in range(num)]
        for i,table_widget in enumerate(table_widgetslist):
            name = Gv.TABBK +'_'+ str(i)
            table_widget.setFixedWidth(width-2)
            table_widget.setFixedHeight(height-5)
            table_widget.setAccessibleName(name)
            table_widget.setObjectName(name)
            self.settableStyle(table_widget, 0)
            table_widget.verticalHeader().setHidden(1)
            table_widgets_new.append(name)
            layout.addWidget(table_widget)
            table_widget.cellClicked.connect(self.on_cell_clicked)
            table_widget.setContextMenuPolicy(Qt.CustomContextMenu)
            table_widget.customContextMenuRequested.connect(self.add_platechar_mueu)
            # 添加数据到表格中


        height_sub = self.groupBox_18.height()
        layout_sub = QHBoxLayout()
        layout_sub.setDirection(QHBoxLayout.RightToLeft)
        self.groupBox_18.setLayout(layout_sub)
        # 创建10个QTableWidget
        table_widgetslist_sub = [QTableWidget(self) for _ in range(num)]
        for i, table_widget_sub in enumerate(table_widgetslist_sub):
            name = Gv.TABBKSUB +'_'+ str(i)
            table_widget_sub.setFixedWidth(width - 2)
            table_widget_sub.setFixedHeight(height_sub - 5)
            table_widget_sub.setAccessibleName(name)
            table_widget_sub.setObjectName(name)
            self.settableStyle(table_widget_sub, 0)
            table_widget_sub.verticalHeader().setHidden(1)
            table_widgets_sub_new.append(name)
            # 添加数据到表格中
            layout_sub.addWidget(table_widget_sub)
            table_widget_sub.cellClicked.connect(self.on_cell_clicked_sub)
            table_widget_sub.setContextMenuPolicy(Qt.CustomContextMenu)
            table_widget_sub.customContextMenuRequested.connect(self.table_widget_sub_Menu)
        #底部
        self.statusbar.showMessage('作者：塞外9楼-追随大师姐快速回本')
        #一键备注
        self.pushButton_bz.clicked.connect(self.onSetBeiZhu)
        #每日复盘选中
        self.tableWidget.clicked.connect(self.onSetTableMrfp)
        #每日复盘筛选
        self.comboBox_mrfp_sx.addItems(['全部','首板','二板','三板','四板','五板','六板','七板','八板','九板'])
        self.comboBox_mrfp_sx.currentIndexChanged.connect(self.on_comboBox_mrfp_sx_changed)
        self.tableWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tableWidget.customContextMenuRequested.connect(self.showMenu)
        self.pushButton_search.clicked.connect(self.on_pushclicked_search)
        self.lineEdit_search.returnPressed.connect(self.on_pushclicked_search)
        self.checkBox_2.setChecked(True)
        #复制
        self.pushButton_copy_name_list.clicked.connect(self.onCopyGpName)
        self.comboBox_copy_index.addItems(['名称','名称|连板数','名称|连板数|板块','板块|个股数','名称+换行'])
        #主板筛选
        self.checkBox_zhuban.stateChanged.connect(self.on_pushclicked_search)
        self.checkBox_delSt.stateChanged.connect(self.on_pushclicked_search)
        self.checkBox_2.stateChanged.connect(self.on_pushclicked_search)

        #早盘竞价
        self.tableWidget_zpjjz.clicked.connect(self.onRowZpjjzClicked)
        self.settableStyle(self.tableWidget_zpjjz, 0)
        self.tableWidget_zpjjz.setAccessibleName(Gv.ZPJJZ)
        self.tableWidget_zpjjz.setSortingEnabled(True)
        self.tableWidget_zpjjz.sortItems(9, Qt.SortOrder.DescendingOrder)


        #市场情绪，更新显示天数
        self.pushButton_2.clicked.connect(self.onSetScqxLineChartShowNum)

        # 设置打开外部网络连接为True
        self.textBrowser_2.setOpenLinks(False)
        self.textBrowser_2.setOpenExternalLinks(False)
        self.textBrowser_2.anchorClicked.connect(self.click_textbrowser)

        #设置
        self.pushButton_set_bz.clicked.connect(self.on_pushButton_set_bz_clicked)
        self.pushButton_set_bz.setAccessibleName(Gv.PUSHBUTTONSETBZ)
        self.pushButton__set_bz_test.clicked.connect(self.on_pushButton_set_bz_test_clicked)
        self.pushButton__set_bz_test.setAccessibleName(Gv.PUSHBUTTONSETBZTEST)
        #标记1
        self.pushButton_set_bz_1.clicked.connect(self.on_pushButton_set_bz_clicked)
        self.pushButton_set_bz_1.setAccessibleName(Gv.PUSHBUTTONSETBZONE)
        #标记9
        self.pushButton_set_bz_9.clicked.connect(self.on_pushButton_set_bz_clicked)
        self.pushButton_set_bz_9.setAccessibleName(Gv.PUSHBUTTONSETBZNINE)
        self.pushButton_set_bz_2_test.clicked.connect(self.on_pushButton_set_bz_test_clicked)
        self.pushButton_set_bz_2_test.setAccessibleName(Gv.PUSHBUTTONSETBZTWO)
        self.pushButton_set_bz_7_test.clicked.connect(self.on_pushButton_set_bz_test_clicked)
        self.pushButton_set_bz_7_test.setAccessibleName(Gv.PUSHBUTTONSETBZSEVEN)
        #设置
        self.comboBox_3.addItems(['缓慢','慢','适中','快'])
        self.comboBox_3.currentIndexChanged.connect(self.on_comboBox_mrfp_czsd_changed)
        self.pushButton_lhb_set.clicked.connect(self.on_lhb_set_clicked)
        self.checkBox_bkldxz.toggled.connect(self.on_radio_button_toggled_bkld)
        self.pushButton_lhb_set_2.clicked.connect(self.on_fd_set_clicked)
        #self.radioButton_3.toggled.connect(self.on_radio_button_toggled)

        #龙虎榜
        self.pushButton_lhb_search.clicked.connect(self.on_pushButton_lhb_table_show_clicked)
        self.tableWidget_lhb_table.clicked.connect(self.onRowLhbClicked)
        #预期设置
        self.tableWidget__yqset.itemClicked.connect(self.onRowYqSetClicked)
        self.pushButton_yq_clear.clicked.connect(self.on_pushButton_yq_clear_clicked)
        self.pushButton_yq_update.clicked.connect(self.on_pushButton_yq_update_clicked)
        self.pushButton_yq_set.clicked.connect(self.on_pushButton_yq_set_clicked)
        self.tableWidget__yqset.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tableWidget__yqset.customContextMenuRequested.connect(self.shwoYqMueu)
        #加入预期
        self.pushButton_add_yuqi.clicked.connect(self.on_yq_add_all)
        #一致数计算
        self.pushButton_fenqi.clicked.connect(self.on_pushButton_fenqi)
        self.pushButton_yizhi.clicked.connect(self.on_pushButton_yizhi)

        #隐藏
        self.label_8.hide()
        self.label_jzhg.hide()
        self.label_9.hide()
        self.label_20.hide()
        self.label_10.hide()
        self.label_21.hide()
        self.checkBox_bkldxz.hide()

    def on_pushButton_yizhi(self):
        numstr = self.lineEdit_yizhi_num.text()
        num = 1
        if numstr is not None and len(numstr)>0:
            num = int(numstr)
            num = num+1
        self.lineEdit_yizhi_num.setText(str(num))

    def on_pushButton_fenqi(self):
        numstr = self.lineEdit_feqni_num.text()
        num = 1
        if numstr is not None and len(numstr)>0:
            num = int(numstr)
            num = num+1
        self.lineEdit_feqni_num.setText(str(num))


    def on_yq_add_all(self):
        #将表格所有加入预期
        self.tableWidget.clearSelection()
        for row in range(self.tableWidget.rowCount()):
            code = self.tableWidget.item(row, 0).text()
            num = self.tableWidget.item(row, 13).text()
            if code is None or len(code)<=0 or num is None or len(num)<=0 or int(num)<2:
                continue
            self.tableWidget.selectRow(row)
            self.onDayExpect()

    def on_fd_set_clicked(self):
        '''封单手数计算'''
        fdnum = self.lineEdit_lhb_id_2.text()
        price = self.lineEdit_lhb_id_3.text()
        if fdnum is None or price is None:
            return
        shou = int((float(fdnum) * 10000) / float(price) / 100)
        self.lineEdit_lhb_id_4.setText(str(shou))
    def on_radio_button_toggled_bkld(self,checked: bool):
        if checked:
            self.tabWidget.setTabText(3,self.checkBox_bkldxz.text())
        else:
            self.tabWidget.setTabText(3,'板块人气')

        self.displayPlateRotation(self.dateEdit.text())

        configFile = {}
        configfileaddr = pathlib.Path(__file__).parent.resolve().as_posix() + '/' + Gv.configfileaddr
        try:
            with open(configfileaddr, 'r') as f:
                configFile = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"Error reading JSON file: {e}")

        configFile[Gv.BKLDISCHECK] = checked
        try:
            with open(configfileaddr, 'w') as f:
                json.dump(configFile, f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"Error reading JSON file: {e}")

    def on_pushButton_yq_set_clicked(self):
        dayexpect_function(self)

    def on_pushButton_yq_update_clicked(self):
        self.tableWidget__yqset.setRowCount(0)
        self.tableWidget__yqset.setColumnCount(0)
        self.dayexpect()
    def on_pushButton_yq_clear_clicked(self):
        '''清空预期'''
        de.clear_data()
        self.tableWidget__yqset.setRowCount(0)
        self.tableWidget__yqset.setColumnCount(0)

        #self.dayexpect()

    def on_lhb_set_clicked(self):
        '''龙虎榜录入'''
        listparam = []
        listparam.append(self.lineEdit_lhb_id.text())
        listparam.append(self.lineEdit_lhb_name.text())
        listparam.append(self.lineEdit_lhb_text_2.text())
        lhb.set_data(listparam)
        self.lineEdit_lhb_text_2.clear()

    def on_item_yqset_changed(self, item: QTableWidgetItem):
        if item is None:
            return
        # 当表格中的项被修改时，这个函数会被调用
        row = item.row()
        column = item.column()
        code = self.tableWidget__yqset.item(row,0).text()
        if code is None or len(code)<=0:
            return
        if column != 6 and column != 7:
            return

        jsondata = {}
        dayexpectfileaddr = pathlib.Path(__file__).parent.resolve().as_posix() +'/'+ Gv.dayexpectfileaddr
        try:
            with open(dayexpectfileaddr, 'r') as f:
                jsondata = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"Error reading JSON file: {e}")
        if jsondata is None:
            return
        list = jsondata.get(code)
        if list is None:
            return
        list[column] = item.text()
        jsondata[code] = list

        try:
            with open(dayexpectfileaddr, 'w') as f:
                json.dump(jsondata, f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"Error reading JSON file: {e}")

    @Slot(QTableWidgetItem)
    def onRowYqSetClicked(self,item):
        if item is None:
            return
        # 获取被点击的单元格的行列索引
        row = self.tableWidget__yqset.row(item)
        col = self.tableWidget__yqset.column(item)
        if col == 6 or col == 7 or col == 9:
            return
        firstRowItem = self.tableWidget__yqset.item(row, 0)
        if firstRowItem is None:
            return
        code = firstRowItem.text()
        if code is None or len(code) <= 0:
            return
        send_code_message(code)
    def onRowLhbClicked(self, index):
        firstRowItem = self.tableWidget_lhb_table.item(index.row(),2)
        if firstRowItem is None:
            return
        code = firstRowItem.text()
        if code is None or len(code) <= 0:
            return
        send_code_message(code)
    def on_pushButton_lhb_table_show_clicked(self):
        self.tableWidget_lhb_table.clear()
        plate_data_all =  lhb.get_lhb_data()
        self.show_table_public(self.tableWidget_lhb_table, plate_data_all)

    def onTabChanged(self):
        tab_index = self.sender().currentIndex()
        dateStr = self.dateEdit.text()
        if dateStr is None or current_time is None:
            return
        self.checkBox_bkldxz.hide()
        #时间切换了，做处理
        if tab_index == 2:
            index = self.comboBox_mrfp_sx.currentIndex()
            if index == 0:
                index = None
            obj = {'datestr': dateStr, 'checkIndex': index, 'checkstate': self.checkBox_2.isChecked(),
                   'search': self.lineEdit_search.text()}
            self.dayReplay(obj)
        elif tab_index == 3:
            self.checkBox_bkldxz.show()
            self.displayPlateRotation(dateStr)
        elif tab_index == 0:
            self.showTableZpjjzData()


    def on_pushButton_set_bz_test_clicked(self):
        configFile = {}
        configfileaddr = pathlib.Path(__file__).parent.resolve().as_posix() + '/' + Gv.configfileaddr
        try:
            with open(configfileaddr, 'r') as f:
                configFile = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"Error reading JSON file: {e}")
        button = self.sender()
        if button.accessibleName() == Gv.PUSHBUTTONSETBZTEST:
            bzList = configFile.get(Gv.BZ)
            type = 0
            bz.bz_Record(bzList,'测试备注',type)
        else:
            check = self.checkBox.isChecked();
            checkBox_numbz = self.checkBox_numbz.isChecked()
            objlist = []
            num = 1
            if button.accessibleName() == Gv.PUSHBUTTONSETBZTWO:
                num = 2
            elif button.accessibleName() == Gv.PUSHBUTTONSETBZSEVEN:
                num = 7
            obj = {'code': '000001', 'text': '测试标记', 'num': num}
            objlist.append(obj)
            param = {'simplecheck': check, 'numcheck': checkBox_numbz, 'list': objlist}
            bz.setBeizhuNew(param)

    def on_pushButton_set_bz_clicked(self):
        button = self.sender()
        if button.text().find('关闭录制') != -1:
            if button.accessibleName() == Gv.PUSHBUTTONSETBZ:
                button.setText('备注录制')
            elif button.accessibleName() == Gv.PUSHBUTTONSETBZONE:
                button.setText('标记1录制')
            elif button.accessibleName() == Gv.PUSHBUTTONSETBZNINE:
                button.setText('标记9录制')
            button.setStyleSheet("")
        else:
            button.setText('关闭录制')
            button.setStyleSheet("background-color: red;")
            if button.accessibleName() == Gv.PUSHBUTTONSETBZ:
                bz.bz_Record(None,None,1)
            elif button.accessibleName() == Gv.PUSHBUTTONSETBZONE:
                bz.bz_Record(None, None, None)
            elif button.accessibleName() == Gv.PUSHBUTTONSETBZNINE:
                configfileaddr = pathlib.Path(__file__).parent.resolve().as_posix() + '/' + Gv.configfileaddr
                configFile = {}
                try:
                    with open(configfileaddr, 'r') as f:
                        configFile = json.load(f)
                except (FileNotFoundError, json.JSONDecodeError) as e:
                    print(f"Error reading JSON file: {e}")
                bzList = configFile.get(Gv.BZONE)
                type = 2
                bz.bz_Record(bzList, None,type)

        # 清空变量
        global bz_location
        #开启监听
        if not test.is_listening:
            test.is_listening = True
            self.thread_bz_listen = test.BzListener()
            self.thread_bz_listen.message_received.connect(self.on_bz_linstener_message_received)
            self.thread_bz_listen.start()
        else:
            test.is_listening = False
            self.thread_bz_listen.quit()
            self.thread_bz_listen.wait()
            #将配置写入文本
            if len(bz_location)>=2:
                configFile = {}
                configfileaddr = pathlib.Path(__file__).parent.resolve().as_posix() + '/' + Gv.configfileaddr
                try:
                    with open(configfileaddr, 'r') as f:
                        configFile = json.load(f)
                except (FileNotFoundError, json.JSONDecodeError) as e:
                    print(f"Error reading JSON file: {e}")
                bzlist = []
                if button.accessibleName() == Gv.PUSHBUTTONSETBZ:
                    bzlist.append(bz_location[0])
                    bzlist.append(bz_location[1])
                    configFile[Gv.BZ] = bzlist
                elif button.accessibleName() == Gv.PUSHBUTTONSETBZONE:
                    configFile[Gv.BZONE] = bzlist
                    bzlist.append(bz_location[0])
                    bzlist.append(bz_location[1])
                    bzlist.append(bz_location[2])
                else:
                    configFile[Gv.BZNINE] = bzlist
                    bzlist.append(bz_location[0])
                    #获取间隔
                    bzOnelist = configFile.get(Gv.BZONE)
                    xystr = bzOnelist[-1]
                    x,y = xystr.split(',')
                    ninex,niney = bz_location[0].split(',')
                    interval = (int(niney) - int(y)) // 8
                    configFile[Gv.INTERVAL] = interval
                try:
                    with open(configfileaddr, 'w') as f:
                        json.dump(configFile, f)
                except (FileNotFoundError, json.JSONDecodeError) as e:
                    print(f"Error reading JSON file: {e}")
            bz_location = []


    def on_bz_linstener_message_received(self,msg):
        print('备注监听鼠标:{}'.format(msg))
        global bz_location
        bz_location.append(msg)


    def customSort(self, item1, item2):
        # 移除“亿”字符并转换为浮点数
        value1 = float(item1.text().rstrip('亿'))
        value2 = float(item2.text().rstrip('亿'))

        # 比较两个值并返回结果
        if value1 < value2:
            return -1
        elif value1 > value2:
            return 1
        else:
            return 0
    def on_pushclicked_search(self):
        print("鼠标已经移出了lineEdit控件！")
        index = self.comboBox_mrfp_sx.currentIndex()
        if index == 0:
            index = None
        obj = {'datestr': mrfp_show_time, 'checkIndex': index, 'checkstate': self.checkBox_2.isChecked(),'search': self.lineEdit_search.text()}
        self.dayReplay(obj)

    def add_platechar_mueu(self,position):
        '''板块轮动菜单'''
        tableWidget = self.sender()
        menuld = QMenu()
        if self.checkBox_bkldxz.isChecked():
            actionld = QAction("加入图表", menuld)
            menuld.addAction(actionld)
            actionld.triggered.connect(lambda: self.add_platechar_mueu_click(tableWidget,0))
            actionldappend = QAction("追加图表", menuld)
            menuld.addAction(actionldappend)
            actionldappend.triggered.connect(lambda: self.add_platechar_mueu_click(tableWidget,1))

        menuld.exec(QCursor.pos())


    def add_platechar_mueu_click(self,tw,sin):
        if tw is None:
            return
        selected_items = tw.selectedItems()
        action_text = None
        for item in selected_items:
            action_text = item.text()
            break
        if action_text is None:
            return
        index = action_text.find('(')
        if index == -1:
            index = action_text.find('[')
        action_text = action_text[:index]
        numstr = self.lineEdit_5.text()
        #将数据生成为html
        if sin == 0:
            mark.showLineChart(numstr=numstr,width=self.web_view.width()-10 ,height=self.web_view.height() - 20,plate=action_text,openstatus=openstatus)
        else:
            mark.appendline(numstr=numstr,width=self.web_view.width()-10 ,height=self.web_view.height() - 20,plate=action_text,openstatus=openstatus)
        # 更改HTML内容并重新加载页面
        fileaddr = pathlib.Path(__file__).parent.resolve().as_posix() + '/' + Gv.lineChartfileaddr
        with open(fileaddr, 'r',encoding='utf-8', errors='ignore') as file:
            html_content = file.read()
        self.web_view.setHtml(html_content)
        self.web_view.update()

    def shwoYqMueu(self,pos):
        '''预期表格添加右键菜单'''
        table = self.sender()
        # 获取点击位置的索引
        index = table.indexAt(pos)
        if not index.isValid():
            return
        row = index.row()
        column = index.column()
        if column == 6:
            menuyq = QMenu()
            action1 = QAction("预期0-3", menuyq)
            action2 = QAction("预期3-5", menuyq)
            action3 = QAction("预期5-7", menuyq)
            action4 = QAction("预期7-10", menuyq)
            action5 = QAction("预期10", menuyq)
            menuyq.addAction(action1)
            menuyq.addAction(action2)
            menuyq.addAction(action3)
            menuyq.addAction(action4)
            menuyq.addAction(action5)
            # 连接动作的信号到槽
            action1.triggered.connect(self.shwoYqMueu_click)
            action2.triggered.connect(self.shwoYqMueu_click)
            action3.triggered.connect(self.shwoYqMueu_click)
            action4.triggered.connect(self.shwoYqMueu_click)
            action5.triggered.connect(self.shwoYqMueu_click)
            menuyq.exec(QCursor.pos())
        if column <=5:
            code = table.item(row, 0).text()
            menuyq = QMenu()
            action1 = QAction("切换持有状态", menuyq)
            menuyq.addAction(action1)
            self.myObject = MyObject()
            action1.triggered.connect(lambda: self.myObject.triggerSignal(MyData(code)))
            self.myObject.mySignal.connect(self.shwoYqMueu_update_hold_status_click)
            menuyq.exec(QCursor.pos())

    def shwoYqMueu_update_hold_status_click(self,data):
        code = data.value
        if code is None or len(code)<=0:
            return
        de.update_hold_status(code)
        self.dayexpect()



    def shwoYqMueu_click(self):
        action_text = self.sender().text()
        if action_text is None:
            return
        action_text = action_text[2:]
        split_result = action_text.split('-')
        if split_result is None or len(split_result)<=0:
            return
        selected_items = self.tableWidget__yqset.selectedItems()
        for item in selected_items:
            column = self.tableWidget__yqset.column(item)
            row = self.tableWidget__yqset.row(item)
            if column % 6 == 0 or column % 7 == 0:
                if column % 6 == 0:
                    itemh = self.tableWidget__yqset.item(row, 7)
                    if len(split_result) >= 2:
                        itemh.setText(split_result[1])
                    else:
                        itemh.setText('')
                    self.tableWidget__yqset.setItem(row, 7, itemh)
                    item.setText(split_result[0])
                    self.tableWidget__yqset.setItem(row,column, item)
                else:
                    if len(split_result) >= 2:
                        item.setText(split_result[1])
                    else:
                        item.setText('')
                    self.tableWidget__yqset.setItem(row, column, item)
                    itemh = self.tableWidget__yqset.item(row,6)
                    itemh.setText(split_result[0])
                    self.tableWidget__yqset.setItem(row,6,itemh)

        #self.on_pushButton_yq_update_clicked()

    def table_widget_sub_Menu(self,position):
        table = self.sender()
        menu = QMenu()
        copyAction = QAction("复制名称", menu)
        # 添加动作到菜单
        menu.addAction(copyAction)
        # 连接动作的信号到槽
        self.myObject = MyObject()
        copyAction.triggered.connect(lambda: self.myObject.triggerSignal(MyData(table)))
        self.myObject.mySignal.connect(self.onCopyGpName_table_widget_sub)
        menu.exec(QCursor.pos())
    def onCopyGpName_table_widget_sub(self,data):
        table = data.value
        name_list = []
        for row in range(table.rowCount()):
            if table.item(row, 0).isSelected():
                code = table.item(row, 0).text()
                if code is None or len(code) <= 0:
                    continue
                name = table.item(row, 1).text()
                name_list.append(name)
        pyperclip.copy(','.join(name_list))


    def showMenu(self,position):
        # 创建菜单
        menu = QMenu()
        editAction = QAction("设置备注", menu)
        menu.addAction(editAction)

        copy = QMenu("复制",self)
        menu.addMenu(copy)
        copyAction = QAction("复制名称", copy)
        copyNumAction = QAction("复制名称|连板数", copy)
        copyNumBKAction = QAction("复制名称|连板数|板块", copy)
        # 添加动作到菜单
        copy.addAction(copyAction)
        copy.addAction(copyNumAction)
        copy.addAction(copyNumBKAction)

        expectAction = QAction("加入预期", menu)
        menu.addAction(expectAction)

        # 连接动作的信号到槽
        editAction.triggered.connect(self.onEdit)
        copyAction.triggered.connect(self.onCopyGpName)
        copyNumAction.triggered.connect(self.onCopyGpName)
        copyNumBKAction.triggered.connect(self.onCopyGpName)
        expectAction.triggered.connect(self.onDayExpect)
        # 计算菜单显示的中心点
        #menu.exec(self.tabWidget.mapToGlobal(position))  # 如果点击位置不在单元格上，则在点击位置显示菜单
        menu.exec(QCursor.pos())

    def onDayExpect(self):
        '''加入预期'''
        selected_items = self.tableWidget.selectedItems()
        if not selected_items:
            return
        jsondata = {}
        dayexpectfileaddr = pathlib.Path(__file__).parent.resolve().as_posix() +'/'+ Gv.dayexpectfileaddr
        try:
            with open(dayexpectfileaddr, 'r') as f:
                jsondata = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"Error reading JSON file: {e}")

        list = []
        code = ''
        other_sign = False
        columnCount = self.tableWidget.columnCount() - 1
        for item in selected_items:
            text = item.text()
            column = self.tableWidget.column(item)
            if column == 0:
                code = text
            if column<5:
                list.append(text)
            elif column == 5:
                if text.find('其他') == -1:
                    list.append(text)
                else:
                    other_sign = True
            elif column == 12 and other_sign == True:
                other_sign = False
                if text.find('；') != -1:
                    text = text[:text.find('；')]
                list[5] = text
            elif column == 13:
                list[3] = text +'连板'
            else:
                list.append('')
            if columnCount == column and len(code)>0:
                jsondata[code] = list
                list = []
                code = ''
        try:
            with open(dayexpectfileaddr, 'w') as f:
                json.dump(jsondata, f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"Error reading JSON file: {e}")



    def onCopyGpName(self):
        action_text = self.sender().text()
        copy_index = self.comboBox_copy_index.currentIndex()
        if action_text is None or copy_index is None:
            return
        name_list = []
        for row in range(self.tableWidget.rowCount()):
            if self.tableWidget.item(row, 0).isSelected():
                code = self.tableWidget.item(row, 0).text()
                if code is None or len(code) <= 0:
                    continue
                name = self.tableWidget.item(row, 1).text()
                num = self.tableWidget.item(row, 13).text()
                text = self.tableWidget.item(row, 5).text()
                if text is not None and text.find('其他') != -1:
                    beizhutext = self.tableWidget.item(row, 12).text()
                    if beizhutext is not None and beizhutext.find('；') != -1:
                        text = beizhutext[:beizhutext.find('；')]
                if action_text.find('板块') != -1:
                    #name_list.append(name + num + ':' + text)
                    name_list.append(text + ':' + name + num)
                elif action_text.find('板数') != -1:
                    name_list.append(name + num)
                else:
                    name_list.append(name)
        if len(name_list)<=0:
            #获取表格全部
            for row in range(self.tableWidget.rowCount()):
                code = self.tableWidget.item(row, 0).text()
                if code is None or len(code) <= 0:
                    continue
                name = self.tableWidget.item(row, 1).text()
                #涨停时间
                zttime = self.tableWidget.item(row, 2).text()
                num = self.tableWidget.item(row, 13).text()
                text = self.tableWidget.item(row, 5).text()
                if text is not None and text.find('其他') != -1:
                    beizhutext = self.tableWidget.item(row, 12).text()
                    if beizhutext is not None and beizhutext.find('；') != -1:
                        text = beizhutext[:beizhutext.find('；')]
                if copy_index == 0:
                    name_list.append(name)
                elif copy_index == 1:
                    name_list.append(name + num)
                elif copy_index == 2:
                    #name_list.append(name+num+':'+text)
                    name_list.append('\n' + text + ':' + name + num)
                elif copy_index == 3:
                    name_list.append(text+':' +name )
                elif  copy_index == 4:
                    name_list.append(name+'\n')
                else:
                    name_list.append(name)
        if self.comboBox_mrfp_sx.currentIndex() >=3 and copy_index == 2:
            #name_list = sorted(name_list, key=lambda item: (-int(item.split(':')[0][-1]), item.split(':')[1]))
            name_list = sorted(name_list, key=lambda item: (-int(
                ''.join(re.findall(r'\d+',item.split(':')[1]))
            ), item.split(':')[0]))
            if name_list:
                first_value = name_list[0]
                name_list[0] = first_value.replace('\n', '')
        if copy_index == 3:
            # 创建一个空字典来存储分类统计结果
            category_count = {}
            # 遍历集合中的每个元素
            for item in name_list:
                # 使用split方法按照冒号分割字符串，得到类别和数量
                category, _ = item.split(":")

                # 如果该类别还未在字典中出现，则初始化计数为1
                # 如果已经存在，则计数加1
                if category not in category_count:
                    category_count[category] = 1
                else:
                    category_count[category] += 1
            # 根据统计结果构建新的列表元素
            name_list = [f"{category}:{count}" for category, count in category_count.items()]
            name_list.sort(key=lambda x: int(x.split(':')[1]), reverse=True)
        if copy_index == 4:
            pyperclip.copy(''.join(name_list))
        else:
            pyperclip.copy(','.join(name_list))
        time.sleep(0.1)
    def onEdit(self):
        '''一键备注'''
        check = self.checkBox.isChecked();
        checkBox_numbz = self.checkBox_numbz.isChecked()
        x, y = pyautogui.position()
        list = []
        for row in range(self.tableWidget.rowCount()):
            if self.tableWidget.item(row,0).isSelected():
                code = self.tableWidget.item(row, 0).text()
                text = self.tableWidget.item(row, 5).text()
                num = self.tableWidget.item(row, 13).text()
                if text is not None and text.find('其他') != -1:
                    beizhutext = self.tableWidget.item(row, 12).text()
                    if beizhutext is not None and beizhutext.find('；') != -1:
                        text = beizhutext[:beizhutext.find('；')]
                if code is None or len(code) <= 0:
                    continue
                obj = {'code':code,'text':text,'num':num}
                list.append(obj)
        param = {'simplecheck': check, 'numcheck': checkBox_numbz,'list':list}
        bz.setBeizhuNew(param)
        win32api.SetCursorPos((x, y))

    def click_textbrowser(self, url: QUrl):
        print('点击了:{}'.format(url.toString()))
        headers = {
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Safari/605.1.15'
        }
        # 去除证书警告
        requests.packages.urllib3.disable_warnings()
        # 发送POST请求
        response = requests.get(url.toString(), headers=headers, verify=False)

    def on_comboBox_mrfp_czsd_changed(self, index):
        '''设置操作速度'''
        configFile = {}
        configfileaddr = pathlib.Path(__file__).parent.resolve().as_posix() + '/' + Gv.configfileaddr
        try:
            with open(configfileaddr, 'r') as f:
                configFile = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"Error reading JSON file: {e}")
        #备注速度
        configFile[Gv.BZSPEED] = index
        try:
            with open(configfileaddr, 'w') as f:
                json.dump(configFile, f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"Error reading JSON file: {e}")

    def on_comboBox_mrfp_sx_changed(self,index):
        '''每日复盘-筛选'''
        if index == 0:
            index = None
        obj = {'datestr': mrfp_show_time, 'checkIndex': index,'checkstate':self.checkBox_2.isChecked(), 'search': self.lineEdit_search.text()}
        self.dayReplay(obj)

    @Slot(int, int)
    def on_cell_clicked(self, row, column):
        table = self.sender()
        dqtable_name = table.accessibleName()
        print(dqtable_name)
        #获取当前板块选中内容
        plateNameold =table.item(row, 0).text()
        if plateNameold is None or len(plateNameold)<=0:
            return
        index = plateNameold.find('(')
        if index == -1:
            index = plateNameold.find('[')
        plateName = plateNameold[:index]
        for table_name in table_widgets_new:


            # 获取 QTableWidget 控件
            tableAll = self.findChild(QTableWidget,table_name)
            isItemName = 0
            for row in range(tableAll.rowCount()):
                # 获取第一列的单元格
                itemtest = tableAll.item(row, 0).text()
                if itemtest is None or len(itemtest)<=0:
                    continue
                #itemtest = itemtest[:itemtest.find('[')]
                if  (table_name == dqtable_name and itemtest == plateNameold) or (table_name != dqtable_name and itemtest.find(plateName) != -1) :
                    tableAll.setStyleSheet("""
                                            QTableWidget::item:selected {
                                                color: black;
                                                font-weight: bold;
                                                background-color: skyblue;
                                                font-size: 11pt;
                                            }
                                           """)
                    tableAll.selectRow(row)
                    isItemName = 1
                    break
            if isItemName == 0:
                tableAll.clearSelection()

        #显示板块下数据
        data = {}
        try:
            bkldisChecked = self.checkBox_bkldxz.isChecked()
            if bkldisChecked:
                jsonfileaddr = pathlib.Path(__file__).parent.resolve().as_posix() + '/' + Gv.jsonfileaddr
            else:
                jsonfileaddr = pathlib.Path(__file__).parent.resolve().as_posix() + '/' + Gv.platepopdataaddr
            with open(jsonfileaddr, 'r') as f:
                data = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"Error reading JSON file: {e}")
        if data is None or not len(data):
            return
        #选中时间后遍历删除大于选中日期的时间
        checkDate = self.dateEdit.text()
        if checkDate is not None and checkDate != current_time:
            for key in list(data.keys()):
                if key > checkDate:
                    del data[key]
        # 获取最后5个键和对应的值
        last_five_items = list(reversed(data.items()))[:num]
        i = 0
        # 打印结果
        for key, value in last_five_items:
            tableSub = self.findChild(QTableWidget, table_widgets_sub_new[i])
            gkxggList = kplAPI.getLimitUpDataListToFromSub(value,plateName,self.checkBox_bkldxz.isChecked())
            self.show_table_public(tableSub,gkxggList)
            i += 1

    @Slot(int, int)
    def on_cell_clicked_sub(self, row, column):
        table = self.sender()
        data = table.item(row, column).text()  # 获取指定单元格的数据（这里假设单元格包含文本）
        # 获取当前板块选中内容
        plateName = table.item(row, 0).text()
        for table_name in table_widgets_sub_new:
            # 获取 QTableWidget 控件
            tableAll = self.findChild(QTableWidget, table_name)
            isitemName = 0
            for row in range(tableAll.rowCount()):
                # 获取第一列的单元格
                itemtest = tableAll.item(row, 0).text()
                if itemtest == plateName:
                    tableAll.setStyleSheet("""
                                                   QTableWidget::item:selected {
                                                       color: black;
                                                       font-weight: bold;
                                                       background-color: skyblue;
                                                       font-size: 11pt;
                                                   }
                                                  """)
                    tableAll.selectRow(row)
                    isitemName = 1
            if isitemName == 0:
                tableAll.clearSelection()
        send_code_message(plateName)
        #显示板块下数据
        data = {}
        try:
            jsonfileaddr = pathlib.Path(__file__).parent.resolve().as_posix() +'/'+ Gv.jsonfileaddr
            with open(jsonfileaddr, 'r') as f:
                data = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"Error reading JSON file: {e}")
        if data is None or not len(data):
            return
        #选中时间后遍历删除大于选中日期的时间
        checkDate = self.dateEdit.text()
        # 将字典的键转换为列表
        keys = list(reversed(data.keys()))
        # 检查键是否在列表中
        if checkDate in keys:
            # 获取键的索引
            key_index = keys.index(checkDate)
            accessibleName = table.accessibleName()
            table_sub_index = int(accessibleName[accessibleName.rfind('_') + 1:])
            global days
            days = (key_index + table_sub_index)
        movedate(days,self.dateEdit.text())


    def onSetTableMrfp(self,index):
        '''每日复盘选中'''
        #
        code = self.tableWidget.item(index.row(), 0).text()
        #判断是否是板块
        if code is None or len(code)<=0:
            return
        #获取备注并显示
        beizhu = self.tableWidget.item(index.row(), 12).text()
        self.textBrowser.setText(beizhu)
        send_code_message(code)
        print('移动次数:{}'.format(days))
        movedate(days, self.dateEdit.text())

    def onSetScqxLineChartShowNum(self):
        '''将折线图显示天数写入配置文件'''
        num = self.lineEdit_5.text();
        if num is None or len(num)<=0:
            return
        jsonfileaddr = pathlib.Path(__file__).parent.resolve().as_posix() + '/' + Gv.configfileaddr
        try:
            with open(jsonfileaddr, 'r') as f:
                data = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"Error reading JSON file: {e}")
        data[Gv.LINECHARTNUM] = int(num)
        # 写入文件
        try:
            with open(jsonfileaddr, 'w') as f:
                json.dump(data, f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"Error reading JSON file: {e}")
        #重新显示折线图
        self.reload_LineChart()


    def onZpjjBkxz(self):
        '''早盘竞价-分类按钮点击事件'''
        button = self.sender()
        accessibleName = button.accessibleName()
        if accessibleName is None:
            return
        if accessibleName.find(Gv.ZPJJZBUT) != -1:
            for item in button_zpjjz:
                if button.accessibleName() is not None and button.accessibleName() == item:
                    button.setStyleSheet("background-color: skyblue;")
                else:
                    button_next = self.findChild(QPushButton,item)
                    button_next.setStyleSheet("")
            for item in button_zpjjz_lb:
                button_next = self.findChild(QPushButton,item)
                button_next.setStyleSheet("")
            plate_data_all = xgbAPI.getUpDataFrame()
            text = button.text()
            text = text[:text.index("[")]
            i = 0
            if text != '全部':
                for index, row in plate_data_all.iterrows():
                    name = str(plate_data_all.iloc[i, 2])
                    if name is not None and len(name) > 0 and name.find(text) == -1:
                        plate_data_all = plate_data_all.drop(index)
                        i -= 1
                    i += 1
            self.show_table_public(self.tableWidget_zpjjz, plate_data_all)
        elif accessibleName.find(Gv.ZPJJZBUTLB) != -1:
            for item in button_zpjjz_lb:
                if button.accessibleName() is not None and button.accessibleName() == item:
                    button.setStyleSheet("background-color: skyblue;")
                else:
                    button_next = self.findChild(QPushButton,item)
                    button_next.setStyleSheet("")
            for item in button_zpjjz:
                button_next = self.findChild(QPushButton,item)
                button_next.setStyleSheet("")
            plate_data_all = xgbAPI.getUpDataFrame()
            text = button.text()
            text = text[:text.index("[")]
            i = 0
            if text != '全部':
                for index, row in plate_data_all.iterrows():
                    name = str(plate_data_all.iloc[i, 11])
                    if name is not None and len(name) > 0 and name.find(text) == -1:
                        plate_data_all = plate_data_all.drop(index)
                        i -= 1
                    i += 1
            #self.tableWidget_zpjjz.clear()
            self.show_table_public(self.tableWidget_zpjjz, plate_data_all)



    def onSetBeiZhu(self):
        '''一键备注'''
        check = self.checkBox.isChecked();
        checkBox_numbz = self.checkBox_numbz.isChecked()
        objlist = []
        for row in range(self.tableWidget.rowCount()):
            code = self.tableWidget.item(row, 0).text()
            text = self.tableWidget.item(row, 5).text()
            num = self.tableWidget.item(row, 13).text()
            if text is not None and text.find('其他') != -1:
                beizhutext = self.tableWidget.item(row, 12).text()
                if beizhutext is not None and beizhutext.find('；') != -1:
                    text = beizhutext[:beizhutext.find('；')]
            if code is None or len(code)<=0:
                continue
            obj = {'code':code,'text':text,'num':num}
            objlist.append(obj)
        mrfp_sx_index = self.comboBox_mrfp_sx.currentIndex()
        if mrfp_sx_index is not None and mrfp_sx_index>=3:
            objlist = sorted(objlist, key=lambda person: (-int(person['num']), person['text']))
        param = {'simplecheck': check, 'numcheck': checkBox_numbz, 'list': objlist}
        bz.setBeizhuNew(param)


    def onRowBkldClicked(self,index):
        print('111')
    def onCheckBoxStateChanged(self):
        '''自动刷新复选框'''
        if self.checkBox_zdsx.isChecked():
            #选中
            print('启用定时----------')
            self.schedulerHandlerImlp(self.comboBox)
            self.schedulerHandlerImlp(self.comboBox_2)
        else:
            #未选中
            print('删除实时盘中定时---------')
            pzbkJobId = jobMap.get(Gv.PZBK)
            pzbkggJobId = jobMap.get(Gv.PZBKXGG)
            scheduler.remove_job(pzbkJobId)
            scheduler.remove_job(pzbkggJobId)
            del jobMap[Gv.PZBK]
            del jobMap[Gv.PZBKXGG]

    def onCheckBoxStateChanged_mrfp_delst(self):
        '''自动刷新复选框'''
        self.tableWidget.clear()
        self.dayReplay({})
    def onComboboxBkSelect(self,index):
        '''
        盘中板块定时选中事件
        :param index:
        :return:
        '''
        if self.checkBox_zdsx.isChecked():
            self.schedulerHandlerImlp(self.comboBox)

    def onComboboxBkGGSelect(self,index):
        '''
        盘中板块下个股定时选中事件
        :param index:
        :return:
        '''
        if self.checkBox_zdsx.isChecked():
            self.schedulerHandlerImlp(self.comboBox_2)

    def onRowClickedBk1Sub(self,index):
        '''板块下个股点击事件'''
        # 获取第一行数据
        firstRowItem = self.tableWidget_bkg1.item(index.row(), 0)
        if firstRowItem is None:
            return
        plateName = firstRowItem.text()
        send_code_message(plateName)
        #pressdownCodeApi(plateName)

    def onRowClickedBk1(self,index):
        '''
        板块轮动-板块点击事件
        :param index:
        :return:
        '''
        # 获取第一行数据
        firstRowItem = self.tableWidget_bk1.item(index.row(), 0)
        if firstRowItem is None:
            return
        plateName = firstRowItem.text()
        bankuaifromsub = kplAPI.getLimitUpDataListToFromSub(self.list, plateName,self.checkBox_bkldxz.isChecked())
        self.show_table_public(self.tableWidget_bkg1, bankuaifromsub)
    def settableStyle(self,table,isHh:bool):

        if isHh:
            # 延伸显示(水平铺满)
            table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
            # 去除行号
            table.verticalHeader().setHidden(1)
        # 设置不可编辑
        table.setEditTriggers(QAbstractItemView.NoEditTriggers)
        # 设置整行选中
        table.setSelectionBehavior(QAbstractItemView.SelectRows)
        table.horizontalHeader().setFont(QFont("Arial", 10, QFont.Bold))
        table.horizontalHeader().setDefaultSectionSize(100)
        #table.headerItem().setBackground(QColor("red"))
        table.horizontalHeader().setStyleSheet("background-color: yellow;")

    def onRowZpjjzClicked(self,index):
        firstRowItem = self.tableWidget_zpjjz.item(index.row(), 0)
        if firstRowItem is None:
            return
        code = firstRowItem.text()
        if code is None or len(code)<=0:
            return
        #获取备注并显示
        beizhu = self.tableWidget_zpjjz.item(index.row(), 12).text()
        self.textBrowser_3.setText(beizhu)
        send_code_message(code)
    def onRowPzbkxggClicked(self,index):
        '''盘中板块下个股点击事件'''
        # 获取第一行数据
        firstRowItem = self.tableWidget_pzbkxgg.item(index.row(), 0)
        if firstRowItem is None:
            return
        code = firstRowItem.text()
        send_code_message(code)
        #pressdownCodeApi(code)
    def onRowClicked(self, index):
        '''
        板块列表点击事件
        :param index:
        :return:
        '''
        # 获取第一行数据
        firstRowItem = self.tableWidget_pzbkrq.item(index.row(), 0)
        if firstRowItem is None:
            return
        plateID = firstRowItem.text()
        self.plateID = plateID
        num = self.lineEdit.text()
        plate_data_Sub_all,upNum = kplAPI.getPlateSubData(num, plateID)
        self.show_table_public(self.tableWidget_pzbkxgg, plate_data_Sub_all)
        text = self.tableWidget_pzbkrq.item(index.row(), 1).text()
        self.label_12.setText(text+'('+str(upNum)+')')
        self.label_12.setStyleSheet('font-size:12pt;')
        #去除板块下个股选中
        self.tableWidget_pzbkxgg.clearSelection()
    def show_table_public(self,tableWidget,plate_data_all):
        '''
        给表格添加数据
        :param tableWidget: 指定表格
        :param plate_data_all: 数据
        :return:
        '''
        if plate_data_all is None:
            return
        row_count = plate_data_all.shape[0]
        col_count = plate_data_all.shape[1]
        radioButtonisChecked = self.checkBox_bkldxz.isChecked()
        # 设置表格行列数
        tableWidget.setRowCount(row_count)
        tableWidget.setColumnCount(col_count)
        tableWidget.setHorizontalHeaderLabels(plate_data_all.columns.tolist())
        accessibleName = tableWidget.accessibleName()
        if accessibleName is not None and len(accessibleName)>0:
            if accessibleName == Gv.ZPJJZ:
                for column in range(tableWidget.columnCount() - 2):
                    tableWidget.setColumnWidth(column, 66)
                tableWidget.setColumnWidth(2, 135)
                tableWidget.setColumnWidth(10, 50)
                tableWidget.setColumnWidth(11, 50)
                tableWidget.setColumnWidth(12, 183)
            if accessibleName == Gv.BKXGG:
                for column in range(tableWidget.columnCount()-2):
                    tableWidget.setColumnWidth(column, 77)
                tableWidget.setColumnWidth(7, 180)
                tableWidget.setColumnWidth(8, 180)
            if accessibleName == Gv.MRFP:
                for column in range(tableWidget.columnCount()):
                    if column == 6:
                        continue
                    tableWidget.setColumnWidth(column, 77)
                tableWidget.setColumnWidth(1, 150)
                tableWidget.setColumnWidth(6, 145)
                tableWidget.setColumnWidth(12, 148)
                tableWidget.setColumnWidth(13, 0)
            if accessibleName == Gv.LHB:
                for column in range(tableWidget.columnCount()):
                    tableWidget.setColumnWidth(column, 77)
                tableWidget.setColumnWidth(3, 295)
                tableWidget.setColumnWidth(9, 300)
            if accessibleName == Gv.YQSZ:
                tableWidget.setColumnWidth(10,0)
            if (accessibleName.find(Gv.TABBK)!=-1 or accessibleName.find(Gv.TABBKSUB)!=-1):
                width = tableWidget.width()
                if accessibleName.find(Gv.TABBKSUB)!=-1:
                    # if tableWidget.rowCount() <= 8:
                    #     width = width - 2
                    # else:
                    #     width = width - 17
                    tableWidget.setColumnWidth(0,0)
                    columnwidth = width/(tableWidget.columnCount()-1)
                    for column in range(tableWidget.columnCount()):
                        if column == 0:
                            continue
                        if column == 2 and tableWidget.rowCount()>8:
                            tableWidget.setColumnWidth(column, columnwidth - 18)
                            continue
                        tableWidget.setColumnWidth(column,columnwidth-1)
                else:
                    if tableWidget.rowCount() <=8:
                        tableWidget.setColumnWidth(0, width - 2)
                    else:
                        tableWidget.setColumnWidth(0, width - 19)

        #将数据添加到表格
        for i in range(row_count):
            code = str(plate_data_all.iloc[i, 0])
            for j in range(col_count):
                value = str(plate_data_all.iloc[i, j])
                item = QTableWidgetItem(value)
                item.setTextAlignment(Qt.AlignCenter)
                if accessibleName is not None and len(accessibleName)>0:
                    if j == 6 and accessibleName == Gv.BKXGG and len(value)>0 and value != '0.0亿':
                        #盘中实时涨停显著
                        item.setBackground(Qt.red)
                    if accessibleName == Gv.MRFP:
                        # 每日复盘
                        if len(code)<=0:
                            item.setBackground(QBrush(QColor(240,248,255)))
                            # 设置单元格的字体样式
                            font = QFont()
                            font.setPointSize(12)
                            font.setBold(True)
                            item.setForeground(QBrush(Qt.red))
                            item.setFont(font)
                    if accessibleName == Gv.LHB:
                        if len(code)<=0:
                            item.setBackground(QBrush(QColor(240,248,255)))
                            # 设置单元格的字体样式
                            font = QFont()
                            font.setPointSize(12)
                            font.setBold(True)
                            item.setForeground(QBrush(Qt.red))
                            item.setFont(font)
                        if j == 4:
                            font = QFont()
                            font.setBold(True)
                            item.setFont(font)
                            if value.find('-') != -1:
                                item.setForeground(QBrush(Qt.green))
                            else:
                                item.setForeground(QBrush(Qt.red))
                        if j == 5:
                            font = QFont()
                            font.setBold(True)
                            item.setFont(font)
                            item.setForeground(QBrush(Qt.red))
                        if j == 6:
                            font = QFont()
                            font.setBold(True)
                            item.setFont(font)
                            item.setForeground(QBrush(Qt.green))
                    if accessibleName == Gv.YQSZ:
                        numStr= str(plate_data_all.iloc[i, 3])
                        numStr = re.search(r'(\d+)连板',numStr).group(1)
                        num = int(numStr)
                        hold_status = plate_data_all.iloc[i, 10]
                        if num > 2:
                            item.setBackground(QBrush(QColor(240, 248, 255)))
                        if hold_status == 1 and j<=5:
                            item.setBackground(QBrush(QColor(230, 10, 30)))
                        if j == 8 or j == 9:
                            if j == 9:
                                value = str(plate_data_all.iloc[i, 8])
                            if j == 8 and value == Gv.dayexpectEnum.value_by_another_value(1):
                                font = QFont()
                                font.setPointSize(12)
                                font.setBold(True)
                                item.setForeground(QBrush(Qt.green))
                                item.setFont(font)
                            elif value == Gv.dayexpectEnum.value_by_another_value(3):
                                font = QFont()
                                font.setPointSize(12)
                                font.setBold(True)
                                item.setForeground(QBrush(Qt.red))
                                item.setFont(font)
                            elif value == Gv.dayexpectEnum.value_by_another_value(4):
                                font = QFont()
                                font.setPointSize(12)
                                font.setBold(True)
                                orange_color = QColor(255, 165, 0)
                                item.setForeground(QBrush(orange_color))
                                item.setFont(font)
                    if accessibleName == Gv.ZPJJZ:
                        lasttime = str(plate_data_all.iloc[i,9])
                        lianbannum = str(plate_data_all.iloc[i,11])
                        if lasttime == '09:25:00' and lianbannum == '首板':
                            item.setBackground(Qt.red)


                    if (accessibleName.find(Gv.TABBK)!=-1 or accessibleName.find(Gv.TABBKSUB)!=-1):
                        if accessibleName.find(Gv.TABBKSUB)!=-1:
                            font = QFont()
                            if j==2:
                                if not radioButtonisChecked:
                                    font.setPointSizeF(7.1)
                                else:
                                    font.setPointSizeF(7.8)
                            else:
                                font.setPointSize(8)

                            item.setFont(font)
                            prefixes = ('30', '68')
                            if any(code.startswith(prefix) for prefix in prefixes) and j==2:
                                item.setText(value+'🔺')
                        else:
                            font = QFont()
                            font.setPointSize(7)
                            item.setFont(font)
                            if radioButtonisChecked and value.find(Gv.ST) == -1 and value.find('其他') == -1:
                                num = int(re.search(r'\[(\d+)\]',value).group(1))
                                if num>=10:
                                    item.setForeground(QtGui.QBrush(QtGui.QColor(255, 0, 0)))


                tableWidget.setItem(i, j, item)

    def closeEvent(self, event):
        print("窗口关闭事件被触发")
        # 关闭定时任务
        scheduler.shutdown(wait=False)
        pid = os.getpid()
        port = get_process_port(pid)
        print('pid:{} port:{}'.format(pid, port))
        if port == port_global:
            try:
                # 杀死进程
                os.kill(pid, 9)
            except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
                print('杀死进程异常')
                pass
        super().closeEvent(event)

    def getBkDataOrShow(self):
        # 获取数据源
        plate_data_all = kplAPI.getPlateData()
        self.show_table_public(self.tableWidget_pzbkrq, plate_data_all)

    def getBkSubDataOrShow(self):
        num = self.lineEdit.text()
        plate_data_Sub_all,upNum= kplAPI.getPlateSubData(num, self.plateID)
        self.show_table_public(self.tableWidget_pzbkxgg, plate_data_Sub_all)
        text = self.label_12.text()
        pattern = r'\((\d+)\)'
        text = re.sub(pattern, f'({upNum})', text)
        self.label_12.setText(text)

    def schedulerHandlerImlp(self,comboBox):
        '''更改定时时间'''
        print('更改了定时时长',comboBox.accessibleName())
        # 获取定时时长
        bkds = self.comboBox.currentText()
        bkggds = self.comboBox_2.currentText()
        current_date = datetime.now().date()
        # 执行定时任务的开始时间和结束时间
        start_time = datetime(current_date.year, current_date.month, current_date.day, 9)
        end_time = datetime(current_date.year, current_date.month, current_date.day, 20)
        if comboBox.accessibleName() == Gv.PZBK:
            if Gv.PZBK in jobMap:
                jobId = jobMap.get(Gv.PZBK)
                scheduler.remove_job(jobId)
            job = scheduler.add_job(bkds_function, 'interval'
                              , seconds=int(bkds)
                              , start_date=start_time.strftime('%Y-%m-%d %H:%M:%S')
                              , end_date=end_time.strftime('%Y-%m-%d %H:%M:%S')
                              , args=[self])
            jobMap[Gv.PZBK] = job.id
        elif comboBox.accessibleName() == Gv.PZBKXGG:
            if Gv.PZBKXGG in jobMap:
                jobId = jobMap.get(Gv.PZBKXGG)
                scheduler.remove_job(jobId)
            job = scheduler.add_job(bkggds_function1, 'interval'
                                    , seconds=int(bkggds)
                                    , start_date=start_time.strftime('%Y-%m-%d %H:%M:%S')
                                    , end_date=end_time.strftime('%Y-%m-%d %H:%M:%S')
                                    , args=[self])
            jobMap[Gv.PZBKXGG] = job.id

    def displayPlateRotation(self,checkDate:None):
        '''读取json文件并显示'''
        print('---读取json文件并显示')
        #清空数据
        for tab in table_widgets_label_new:
            label = self.findChild(QLabel,tab)
            label.setText("")
        for tab in table_widgets_new:
            table = self.findChild(QTableWidget,tab)
            table.setRowCount(0)
            table.setColumnCount(0)
        for tab in table_widgets_sub_new:
            table = self.findChild(QTableWidget,tab)
            table.setRowCount(0)
            table.setColumnCount(0)
        # 读取文件
        data = {}
        try:
            bkldisChecked = self.checkBox_bkldxz.isChecked()
            if bkldisChecked:
                jsonfileaddr = pathlib.Path(__file__).parent.resolve().as_posix() +'/'+ Gv.jsonfileaddr
            else:
                jsonfileaddr = pathlib.Path(__file__).parent.resolve().as_posix() + '/' + Gv.platepopdataaddr
            with open(jsonfileaddr, 'r') as f:
                data = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"Error reading JSON file: {e}")
        if data is None or not len(data):
            return
        #读取大盘数据
        data_label = {}
        try:
            hreadfileaddr = pathlib.Path(__file__).parent.resolve().as_posix() + '/' + Gv.hreadfileaddr
            with open(hreadfileaddr, 'r') as f:
                data_label = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"Error reading JSON file: {e}")
        #选中时间后遍历删除大于选中日期的时间
        if checkDate is not None:
            for key in list(data.keys()):
                if key > checkDate:
                    del data[key]
            for key in list(data_label.keys()):
                if  key > checkDate:
                    del data_label[key]

        # 获取最后5个键和对应的值
        last_five_items = list(reversed(data.items()))[:num]
        i = 0
        # 打印结果
        for key, value in last_five_items:
            plate_data_all = kplAPI.getLimitUpDataListToFrom(key,value)
            table = self.findChild(QTableWidget, table_widgets_new[i])
            self.show_table_public(table,plate_data_all)
            # 显示大盘数据
            dapan = data_label.get(key)
            if dapan is not None and len(dapan) > 0:
                label = self.findChild(QLabel, table_widgets_label_new[i])
                rise_count = dapan.get('rise_count')
                fall_count = dapan.get('fall_count')
                size = str(5)
                label.setText('<font color="red"  size=' + size + '>' + str(
                    rise_count) + '</font> | <font color="green" size=' + size + '>' + str(fall_count) + '</font>')
                label.setAlignment(Qt.AlignCenter)
            i += 1

    def dayexpect(self):
        '''每日预期'''
        plate_data_all = de.get_dayexpect_data()
        self.show_table_public(self.tableWidget__yqset, plate_data_all)
        self.tableWidget__yqset.itemChanged.connect(self.on_item_yqset_changed)
        over_3_probability,under_3_probability = de.get_dayexpect_emotion()
        if over_3_probability is not None:
            if over_3_probability > 50:
                self.label_35.setStyleSheet("color: green; font-size: 16px; font-family: Arial;font-weight: bold;")
            else:
                self.label_35.setStyleSheet("color: red; font-size: 16px; font-family: Arial;font-weight: bold;")
            text = str(round(over_3_probability))+'%分歧'
            self.label_35.setText(text)

        if under_3_probability is not None:
            if under_3_probability > 50:
                self.label_37.setStyleSheet("color: green; font-size: 16px; font-family: Arial;font-weight: bold;")
            else:
                self.label_37.setStyleSheet("color: red; font-size: 16px; font-family: Arial;font-weight: bold;")
            text = str(round(under_3_probability)) + '%分歧'
            self.label_37.setText(text)

    def dayReplay(self,obj):
        '''每日复盘'''
        print('每日复盘')
        #obj = {'datestr': self.dateEdit.text(), 'checkIndex': index, 'search': None}
        checkDate = obj.get('datestr')
        checkIndex = obj.get('checkIndex')
        searchstr = obj.get('search')
        checkstate = obj.get('checkstate')
        data = {}
        jsonfileaddr = pathlib.Path(__file__).parent.resolve().as_posix() + '/' + Gv.jsonfileaddr
        try:
            with open(jsonfileaddr, 'r') as f:
                data = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"Error reading JSON file: {e}")

        isDelSt = self.checkBox_delSt.isChecked()
        isZhuban = self.checkBox_zhuban.isChecked()
        last_five_items = []
        if checkDate is None:
            #默认进入
            last_five_items = list(reversed(data.items()))[:1]
        else:
            #选中日期控件
            items = data.get(checkDate)
            last_five_items.append((checkDate,items))
            #设置位移天数
            self.count_keys_after(data,checkDate)
        if last_five_items is None or len(last_five_items)<=0:
            return
        global mrfp_show_time
        for key, value in last_five_items:
            mrfp_show_time = key
            requestData = value
            if requestData is None:
                return
            plate_data_all = kplAPI.geteverydayReplay(requestData)
            if plate_data_all is None:
                continue

            time_format = "%H:%M:%S"
            ztsjpzt = datetime.strptime('11:25:00', time_format).time()
            ztsjpzw = datetime.strptime('13:05:00', time_format).time()
            ztsjjj = datetime.strptime('9:30:00', time_format).time()
            prefixes = ('30', '68')
            searchlist = ['']
            if searchstr is not None:
                searchlist = searchstr.split(';')
            for search in searchlist:
                i = 0
                mark = None
                nameindex = None
                for index,row in plate_data_all.iterrows():
                    flag = i
                    codeText = str(plate_data_all.iloc[i, 0])
                    name = str(plate_data_all.iloc[i, 1])
                    #板数
                    ztnum = str(plate_data_all.iloc[i, 13])
                    beizhuText = str(plate_data_all.iloc[i, 12])
                    plateText = str(plate_data_all.iloc[i, 6])
                    sfkbStr= str(plate_data_all.iloc[i, 7])

                    ztsjstr = str(plate_data_all.iloc[i, 2])
                    ltszStr = str(plate_data_all.iloc[i, 4])
                    ztsj = None
                    if ztsjstr is not None and len(ztsjstr)>0:
                        ztsj = datetime.strptime(str(plate_data_all.iloc[i, 2]), time_format).time()


                    if name is not None and len(name)>0 and isDelSt and name.find(Gv.ST)!=-1 and codeText is not None and len(codeText)>0:
                        # 去除ST
                        plate_data_all = plate_data_all.drop(index)
                        i-=1
                    elif codeText is not None and len(codeText)>0 and isZhuban and any(codeText.startswith(prefix) for prefix in prefixes):
                        # 去除非主板
                        plate_data_all = plate_data_all.drop(index)
                        i -= 1
                    elif  checkIndex is not None and ztnum is not None and len(ztnum)>0 and  checkstate is not None and (checkIndex > int(ztnum) and checkstate) :
                        #去除 大于选中板块数
                        plate_data_all = plate_data_all.drop(index)
                        i -= 1
                    elif checkIndex is not None and ztnum is not None and len(ztnum) > 0 and checkstate is not None and (checkIndex != int(ztnum) and not checkstate):
                        # 去除 大于选中板块数
                        plate_data_all = plate_data_all.drop(index)
                        i -= 1
                    elif search is not None and len(search)>0:
                        if search.find('盘中')!=-1:
                            if ztsj is not None and (ztsj<ztsjpzt or ztsj>ztsjpzw):
                                plate_data_all = plate_data_all.drop(index)
                                i -= 1
                            elif ztsj is not None and search.find('是')==-1 and sfkbStr is not None and sfkbStr.find('否') == -1:
                                plate_data_all = plate_data_all.drop(index)
                                i -= 1
                        elif search.find('一字') != -1 or search.find('一') != -1 or search.find('T字') != -1 or search.find('T') != -1:
                            if search.find('一字') != -1 or search.find('一') != -1 :
                                if ztsj is not None and (ztsj > ztsjjj):
                                    plate_data_all = plate_data_all.drop(index)
                                    i -= 1
                                elif ztsj is not None and search.find('是') == -1 and sfkbStr is not None and sfkbStr.find('否') == -1:
                                    plate_data_all = plate_data_all.drop(index)
                                    i -= 1
                            elif  search.find('T字') != -1 or search.find('T') != -1:
                                ztsjjjt = datetime.strptime('9:30:03', time_format).time()
                                if ztsj is not None and (ztsj > ztsjjjt):
                                    plate_data_all = plate_data_all.drop(index)
                                    i -= 1
                        elif search.find('市值') != -1 and ltszStr is not None and len(ltszStr)>0:
                            # 流通市值
                            ltszfo = float(ltszStr[:-1])
                            paramltsz = float(re.split('>|<',search)[1])
                            if search.find('<') != -1 and ltszfo > paramltsz:
                                plate_data_all = plate_data_all.drop(index)
                                i -= 1
                            elif search.find('>') != -1 and ltszfo < paramltsz:
                                plate_data_all = plate_data_all.drop(index)
                                i -= 1
                        elif search.find('时间') != -1 and ztsj is not None:
                            ztsjsearchlist = re.split('>|<', search)
                            if len(ztsjsearchlist) == 2:
                                paramztsj = datetime.strptime(re.split('>|<', search)[1]+':00', time_format).time()
                                if search.find('<') != -1 and ztsj > paramztsj:
                                    plate_data_all = plate_data_all.drop(index)
                                    i -= 1
                                elif search.find('>') != -1 and ztsj < paramztsj:
                                    plate_data_all = plate_data_all.drop(index)
                                    i -= 1
                            elif len(ztsjsearchlist) == 3:
                                paramztsjbefore= datetime.strptime(re.split('>|<', search)[0]+':00', time_format).time()
                                paramztsjalter = datetime.strptime(re.split('>|<', search)[2]+':00', time_format).time()
                                if ztsj < paramztsjbefore or ztsj>paramztsjalter:
                                    plate_data_all = plate_data_all.drop(index)
                                    i -= 1
                        else:
                            if (plateText is not None and len(plateText) > 0 and plateText.find(search) == -1
                                    and (beizhuText is not None and len(beizhuText) > 0 and beizhuText.find(search) == -1)
                                    and (codeText is not None and len(codeText) > 0 and codeText.find(search) == -1)
                                    and (name is not None and len(name) > 0 and name.find(search) == -1)):
                                plate_data_all = plate_data_all.drop(index)
                                i -= 1

                    if name is not None and len(name)>0 and (codeText is None or len(codeText)<=0) and len(ztnum)<=0:
                        #板块
                        if mark is not None and nameindex is not None and mark == (i - 1):
                            plate_data_all = plate_data_all.drop(nameindex)
                            i -= 1
                        mark = i
                        nameindex = index
                    i += 1
            row_count = plate_data_all.shape[0]
            if row_count>=1:
                zuihouindex = row_count - 1
                codeText = str(plate_data_all.iloc[zuihouindex, 0])
                if codeText is None or len(codeText)<=0:
                    # 去除最后一列
                    plate_data_all = plate_data_all.iloc[:-1]
                self.show_table_public(self.tableWidget, plate_data_all)



        #设置配置文件回显
        configfileaddr = pathlib.Path(__file__).parent.resolve().as_posix() + '/' + Gv.configfileaddr
        try:
            with open(configfileaddr, 'r') as f:
                configData = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"Error reading JSON file: {e}")

        if configData is not None and len(configData)>0:
            LINECHARTNUM = configData.get(Gv.LINECHARTNUM)
            BZSPEED = configData.get(Gv.BZSPEED)
            self.lineEdit_5.setText(str(LINECHARTNUM))
            if BZSPEED is None:
                self.comboBox_3.setCurrentIndex(2)
            else:
                self.comboBox_3.setCurrentIndex(BZSPEED)
            BKLDISCHECK = configData.get(Gv.BKLDISCHECK)
            if BKLDISCHECK:
                self.checkBox_bkldxz.setChecked(True)
            else:
                self.checkBox_bkldxz.setChecked(False)


    def count_keys_after(self,data,key):
        # 将字典的键转换为列表
        keys = list(reversed(data.keys()))
        # 检查键是否在列表中
        if key not in keys:
            return
        # 获取键的索引
        key_index = keys.index(key)
        global days
        days = key_index


    def setFontColor(self,font,color,table):
        table.setFont(font)
        palette = table.palette()
        palette.setColor(QPalette.WindowText, color)  # 红色文本
        table.setPalette(palette)

    def showTableHeadData(self):
        print('----显示头部数据-------')
        fontda = QFont("Arial", 20)
        font = QFont("Arial")
        font.setBold(True)
        font.setPointSize(10)
        colorred = QColor("red")
        colorgreen = QColor("green")
        #显示头部数据
        #热度
        temperature = xgbAPI.getTemperatureData()
        global hreaddata
        hreaddatacur = {}
        if temperature is not None:
            market_temperature = temperature['market_temperature']
            self.label_redu.setText(str(int(market_temperature))+'%')
            self.setFontColor(fontda,colorred,self.label_redu)
        #涨跌
        if hreaddata is not None and len(hreaddata)>0:
            riseFall = xgbAPI.getRiseFallCountData()
            if riseFall is not None:
                rise_count = riseFall['rise_count']
                fall_count = riseFall['fall_count']
                self.label_jzsz.setText(str(hreaddata.get('rise_count'))+'|'+ str(rise_count))
                self.label_jzxd.setText(str(hreaddata.get('fall_count'))+ '|' + str(fall_count))
                self.setFontColor(font,colorred, self.label_jzsz)
                self.setFontColor(font,colorgreen, self.label_jzxd)
                hreaddatacur['rise_count'] = rise_count
                hreaddatacur['fall_count'] = fall_count
                #冰点提示
                freezpointTios(self.radioButton_5.isChecked(),rise_count)
            #涨跌停
            upDown = xgbAPI.getUpDownData()
            yesterday = xgbAPI.getYesterdayData()
            if upDown is not None:
                limit_up_count = upDown['limit_up_count']
                limit_down_count = upDown['limit_down_count']
                self.label_jzdt.setText(hreaddata.get('limit_down_count') +'|'+str(limit_down_count))
                if yesterday is not None:
                    yesterday_limit_up_avg_pcp = yesterday['yesterday_limit_up_avg_pcp']
                    self.label_jzlbyj.setText(hreaddata.get('limit_up_count')+'-'+str(hreaddata.get('yesterday_limit_up_avg_pcp'))+'|'+ str(limit_up_count) + '-'+str(round(yesterday_limit_up_avg_pcp * 100, 2))+'%')
                    hreaddatacur['yesterday_limit_up_avg_pcp'] = str(round(yesterday_limit_up_avg_pcp * 100, 2))+'%'
                else:
                    self.label_jzlbyj.setText(str(hreaddata.get('limit_up_count')) +'|'+str(limit_up_count))
                self.setFontColor(font,colorgreen, self.label_jzdt)
                self.setFontColor(font,colorred, self.label_jzlbyj)
                hreaddatacur['limit_up_count'] = str(limit_up_count)
                hreaddatacur['limit_down_count'] = str(limit_down_count)
            #炸板
            broken = xgbAPI.getBrokenData()
            if broken is not None:
                limit_up_broken_count = broken['limit_up_broken_count']
                limit_up_broken_ratio = broken['limit_up_broken_ratio']
                self.label_jzzbl.setText(hreaddata.get('limit_up_broken_count')+'-'+hreaddata.get('limit_up_broken_ratio') +'|'+ str(limit_up_broken_count) +'-'+ str(int(limit_up_broken_ratio * 100))+'%')
                self.setFontColor(font,colorgreen, self.label_jzzbl)
                hreaddatacur['limit_up_broken_count'] = str(limit_up_broken_count)
                hreaddatacur['limit_up_broken_ratio'] = str(int(limit_up_broken_ratio * 100))+'%'
            #上证量
            shangShenZhenVol = dfcfAPI.getShangShenZhenVol()
            if shangShenZhenVol is not None and len(shangShenZhenVol)>=2:
                szVol = str(round(shangShenZhenVol[0].get('f6') / 100000000)) + '亿'
                allVol = str(round((shangShenZhenVol[0].get('f6') + shangShenZhenVol[1].get('f6')) / 100000000)) + '亿'
                self.label_jzszl.setText(hreaddata.get('szVol') +'|'+szVol)
                self.label_jzqsl.setText(hreaddata.get('allVol')+'|'+ allVol)
                self.setFontColor(font, colorred, self.label_jzszl)
                self.setFontColor(font, colorred, self.label_jzqsl)
                hreaddatacur['szVol'] = szVol
                hreaddatacur['allVol'] = allVol
            #北向资金
            # beiXiangMoney = dfcfAPI.getBeiXiangMoney()
            # if beiXiangMoney is not None:
            #     hk2sh = beiXiangMoney.get('hk2sh')
            #     #上证
            #     if hk2sh is not None:
            #         netBuyAmt = round(hk2sh.get('netBuyAmt') / 10000,2)
            #         self.label_jzhg.setText(hreaddata.get('hk2sh')+'|'+str(netBuyAmt)+'亿')
            #         self.setFontColor(font, colorred if netBuyAmt>=0 else colorgreen, self.label_jzhg)
            #         hreaddatacur['hk2sh'] = str(netBuyAmt)
            #     #深证
            #     hk2sz = beiXiangMoney.get('hk2sz')
            #     if hk2sz is not None:
            #         netBuyAmt = round(hk2sz.get('netBuyAmt') / 10000, 2)
            #         self.label_20.setText(hreaddata.get('hk2sz')+'|'+str(netBuyAmt) + '亿')
            #         self.setFontColor(font, colorred if netBuyAmt >= 0 else colorgreen, self.label_20)
            #         hreaddatacur['hk2sz'] = str(netBuyAmt)
            #     #北向合计
            #     if hk2sh is not None and hk2sz is not None:
            #         netBuyAmtAll = round((hk2sh.get('netBuyAmt') + hk2sz.get('netBuyAmt')) / 10000, 2)
            #         self.label_21.setText(hreaddata.get('hk2all')+'|'+str(netBuyAmtAll) + '亿')
            #         self.setFontColor(font, colorred if netBuyAmtAll >= 0 else colorgreen, self.label_21)
            #         hreaddatacur['hk2all'] = str(netBuyAmtAll)
        else:
            riseFall = xgbAPI.getRiseFallCountData()
            if riseFall is not None:
                rise_count = riseFall['rise_count']
                fall_count = riseFall['fall_count']
                self.label_jzsz.setText(str(rise_count))
                self.label_jzxd.setText(str(fall_count))
                self.setFontColor(font, colorred, self.label_jzsz)
                self.setFontColor(font, colorgreen, self.label_jzxd)
                hreaddatacur['rise_count'] = rise_count
                hreaddatacur['fall_count'] = fall_count
                # 冰点提示
                freezpointTios(self.radioButton_5.isChecked(),rise_count)
            # 涨跌停
            upDown = xgbAPI.getUpDownData()
            yesterday = xgbAPI.getYesterdayData()
            if upDown is not None:
                limit_up_count = upDown['limit_up_count']
                limit_down_count = upDown['limit_down_count']
                self.label_jzdt.setText(str(limit_down_count))
                if yesterday is not None:
                    yesterday_limit_up_avg_pcp = yesterday['yesterday_limit_up_avg_pcp']
                    self.label_jzlbyj.setText(str(limit_up_count) + '-' + str(
                        round(yesterday_limit_up_avg_pcp * 100, 2)) + '%')
                    hreaddatacur['yesterday_limit_up_avg_pcp'] = str(
                        round(yesterday_limit_up_avg_pcp * 100, 2)) + '%'
                else:
                    self.label_jzlbyj.setText(str(limit_up_count))
                self.setFontColor(font, colorgreen, self.label_jzdt)
                self.setFontColor(font, colorred, self.label_jzlbyj)
                hreaddatacur['limit_up_count'] = str(limit_up_count)
                hreaddatacur['limit_down_count'] = str(limit_down_count)
            # 炸板
            broken = xgbAPI.getBrokenData()
            if broken is not None:
                limit_up_broken_count = broken['limit_up_broken_count']
                limit_up_broken_ratio = broken['limit_up_broken_ratio']
                self.label_jzzbl.setText(str(limit_up_broken_count) + '-' + str(
                    int(limit_up_broken_ratio * 100)) + '%')
                self.setFontColor(font, colorgreen, self.label_jzzbl)
                hreaddatacur['limit_up_broken_count'] = str(limit_up_broken_count)
                hreaddatacur['limit_up_broken_ratio'] = str(int(limit_up_broken_ratio * 100)) + '%'
            # 上证量
            shangShenZhenVol = dfcfAPI.getShangShenZhenVol()
            if shangShenZhenVol is not None and len(shangShenZhenVol) >= 2:
                szVol = str(round(shangShenZhenVol[0].get('f6') / 100000000)) + '亿'
                allVol = str(
                    round((shangShenZhenVol[0].get('f6') + shangShenZhenVol[1].get('f6')) / 100000000)) + '亿'
                self.label_jzszl.setText(szVol)
                self.label_jzqsl.setText(allVol)
                self.setFontColor(font, colorred, self.label_jzszl)
                self.setFontColor(font, colorred, self.label_jzqsl)
                hreaddatacur['szVol'] = szVol
                hreaddatacur['allVol'] = allVol
            # 北向资金
            # beiXiangMoney = dfcfAPI.getBeiXiangMoney()
            # if beiXiangMoney is not None:
            #     hk2sh = beiXiangMoney.get('hk2sh')
            #     # 上证
            #     if hk2sh is not None:
            #         netBuyAmt = round(hk2sh.get('netBuyAmt') / 10000, 2)
            #         self.label_jzhg.setText(str(netBuyAmt) + '亿')
            #         self.setFontColor(font, colorred if netBuyAmt >= 0 else colorgreen, self.label_jzhg)
            #         hreaddatacur['hk2sh'] = str(netBuyAmt)
            #     # 深证
            #     hk2sz = beiXiangMoney.get('hk2sz')
            #     if hk2sz is not None:
            #         netBuyAmt = round(hk2sz.get('netBuyAmt') / 10000, 2)
            #         self.label_20.setText(str(netBuyAmt) + '亿')
            #         self.setFontColor(font, colorred if netBuyAmt >= 0 else colorgreen, self.label_20)
            #         hreaddatacur['hk2sz'] = str(netBuyAmt)
            #     # 北向合计
            #     if hk2sh is not None and hk2sz is not None:
            #         netBuyAmtAll = round(hk2sh.get('netBuyAmt') / 10000, 2) + round(hk2sz.get('netBuyAmt') / 10000,
            #                                                                         2)
            #         self.label_21.setText(str(netBuyAmtAll) + '亿')
            #         self.setFontColor(font, colorred if netBuyAmtAll >= 0 else colorgreen, self.label_21)
            #         hreaddatacur['hk2all'] = str(netBuyAmtAll)
        if openstatus <= 0:
            hreaddata = hreaddatacur

    def showTableZpjjzData(self):
        print('----显示早盘晋级涨数据------')
        self.tableWidget_zpjjz.setRowCount(0)
        self.tableWidget_zpjjz.setColumnCount(0)

        layout = self.groupBox_4.layout()
        lianban_layout = self.groupBox_7.layout()
        if layout is None:
            layout = QVBoxLayout()
            layout.setAlignment(Qt.AlignLeft)
            self.groupBox_4.setLayout(layout)
        else:
            while layout.count():
                item = layout.takeAt(0)
                widget = item.widget()
                if widget is not None:
                    widget.deleteLater()
        if lianban_layout is None:
            lianban_layout = QVBoxLayout()
            lianban_layout.setAlignment(Qt.AlignLeft)
            self.groupBox_7.setLayout(lianban_layout)
        else:
            while lianban_layout.count():
                item = lianban_layout.takeAt(0)
                widget = item.widget()
                if widget is not None:
                    widget.deleteLater()


        plate_data_all = xgbAPI.getUpDataFrame()
        self.show_table_public(self.tableWidget_zpjjz, plate_data_all)
        row_count = plate_data_all.shape[0]
        value_num_obj = {}
        lianban_num_obj={}
        for i in range(row_count):
            value = str(plate_data_all.iloc[i,2])
            lianban = str(plate_data_all.iloc[i,11])
            if value.find(Gv.JHFG) != -1:
                valueList = value.split(Gv.JHFG)
                for item in valueList:
                    num = value_num_obj.get(item)
                    if num is None:
                        value_num_obj[item] = 1
                    else:
                        value_num_obj[item] = num + 1
            else:
                num = value_num_obj.get(value)
                if num is None:
                    value_num_obj[value] = 1
                else:
                    value_num_obj[value] = num + 1
            lianban_num = lianban_num_obj.get(lianban)
            if lianban_num is None:
                lianban_num_obj[lianban] = 1
            else:
                lianban_num_obj[lianban] = lianban_num + 1
        value_num_obj['全部'] = row_count
        sorted_items = sorted(value_num_obj.items(), key=lambda item: item[1], reverse=True)
        lianban_sorted_items = sorted(lianban_num_obj.items(), key=lambda item: item[1], reverse=True)
        num = 10
        width = self.groupBox_4.width()
        height = (self.groupBox_4.height()-2) // num
        height = (self.groupBox_4.height() - 2 - height) // num
        #TODO
        #layout = QVBoxLayout()
        #layout.setAlignment(Qt.AlignLeft)
        #self.groupBox_4.setLayout(layout)
        global button_zpjjz,button_zpjjz_lb
        button_zpjjz_bd = []
        button_zpjjz_bd_lb = []
        i = 0
        for key,val in sorted_items:
            if i>= num:
                break
            button = QPushButton(key +'['+str(val)+']', self.groupBox_4)
            button.setFixedWidth(width-15)
            button.setFixedHeight(height)
            name= Gv.ZPJJZBUT + str(i)
            button.setObjectName(name)
            button.setAccessibleName(name)
            button_zpjjz_bd.append(name)
            if len(key)>6:
                font = QFont("Microsoft YaHei",7)
                button.setFont(font)
            button.clicked.connect(self.onZpjjBkxz)
            layout.addWidget(button)
            i+=1
        button_zpjjz = button_zpjjz_bd
        #连板分类
        lianban_width = self.groupBox_7.width()
        lianban_height = (self.groupBox_7.height() - 2) // num
        lianban_height = (self.groupBox_7.height() - 2 - lianban_height) // num
        #TODO
        # lianban_layout = QVBoxLayout()
        # lianban_layout.setAlignment(Qt.AlignLeft)
        #self.groupBox_7.setLayout(lianban_layout)
        lianban_i = 0
        for key, val in lianban_sorted_items:
            if lianban_i >= num:
                break
            lianban_button = QPushButton(key + '[' + str(val) + ']', self.groupBox_7)
            lianban_button.setFixedWidth(lianban_width - 15)
            lianban_button.setFixedHeight(lianban_height)
            #标识
            name_lb = Gv.ZPJJZBUTLB + str(lianban_i)
            lianban_button.setObjectName(name_lb)
            lianban_button.setAccessibleName(name_lb)
            button_zpjjz_bd_lb.append(name_lb)
            if len(key) > 6:
                font = QFont("Microsoft YaHei", 7)
                lianban_button.setFont(font)
            lianban_button.clicked.connect(self.onZpjjBkxz)
            lianban_layout.addWidget(lianban_button)
            lianban_i += 1
        button_zpjjz_lb = button_zpjjz_bd_lb

    def onDateChanged(self, date):
        # 处理选中的日期
        datestr = date.toString("yyyy-MM-dd")
        currentIndex = self.tabWidget.currentIndex()
        if currentIndex == 2:
            index = self.comboBox_mrfp_sx.currentIndex()
            if index == 0:
                index = None
            obj = {'datestr': datestr, 'checkIndex': index, 'checkstate': self.checkBox_2.isChecked(),
                   'search': self.lineEdit_search.text()}
            self.dayReplay(obj)
        elif currentIndex == 3:
            self.displayPlateRotation(datestr)

    def reload_LineChart(self):
        print('-----重新加载市场情绪.折线图')
        numstr = self.lineEdit_5.text()
        #将数据生成为html
        mark.showLineChart(numstr=numstr,width=self.web_view.width()-10 ,height=self.web_view.height() - 20,openstatus=openstatus)
        # 更改HTML内容并重新加载页面
        fileaddr = pathlib.Path(__file__).parent.resolve().as_posix() + '/' + Gv.lineChartfileaddr
        with open(fileaddr, 'r',encoding='utf-8', errors='ignore') as file:
            html_content = file.read()
        self.web_view.setHtml(html_content)
        #self.web_view.reload()
        self.web_view.update()

    def showLineChart(self):
        '''显示折线图'''
        print('----市场情绪.折线图')
        width = self.groupBox_scqx.width()
        height = self.groupBox_scqx.height()
        numstr = self.lineEdit_5.text()
        self.web_view = QWebEngineView()
        self.web_view.setFixedWidth(width -2)
        self.web_view.setFixedHeight(height -5)
        #将数据生成为html
        mark.showLineChart(numstr=numstr,width=self.web_view.width()-10 ,height=self.web_view.height() - 20,openstatus=openstatus)

        fileaddr = pathlib.Path(__file__).parent.resolve().as_posix() + '/' + Gv.lineChartfileaddr
        with open(fileaddr, 'r',encoding='utf-8', errors='ignore') as file:
            html_content = file.read()
        self.web_view.setHtml(html_content)
        layout = QVBoxLayout()
        layout.addWidget(self.web_view)
        self.groupBox_scqx.setLayout(layout)

    def on_message_received(self,msg):
        self.textBrowser_2.append(msg)
        self.textBrowser_2.append('')

    def on_http_message_received(self,msg):
        print('http信号槽收到消息:{}'.format(msg))
        send_code_message(msg)

    def save_plate_rq(self,plate_data_all):
        '''保存板块人气数据'''
        print('保存板块人气数据-----')
        if openstatus>0:
            return
        if plate_data_all is None:
            return
        jsonfileaddr = pathlib.Path(__file__).parent.resolve().as_posix() + '/' + Gv.jsonfileaddr
        # 读取文件
        data = {}
        try:
            with open(jsonfileaddr, 'r') as f:
                data = json.load(f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"Error reading JSON file: {e}")
        firstData =  data.get(current_time)
        if firstData is None or len(firstData)<=0:
            return
        first_name_data = plate_data_all.iloc[:,1]
        save_plate_code = []
        for item in firstData:
            ZSPop = item.get('ZSPop')
            ZSName = item.get('ZSName')
            if ZSPop is not None:
                return
            for index,name in enumerate(first_name_data):
                if ZSName.find(name) != -1:
                    platecode = plate_data_all.iloc[index, 0]
                    platepop = plate_data_all.iloc[index, 2]
                    save_plate_code.append(platecode)
                    ZSPop = platepop
                    break
                    #not_save_plate[platecode] = {'ZSCode':platecode,'ZSName':name,'TCExplain':'','StockList':[],'num':0,'ZSPop':platepop}

            if ZSPop is None or len(str(ZSPop))<=0:
                ZSPop = 0
            item['ZSPop'] = ZSPop

        first_code_data = plate_data_all.iloc[:,0]
        for index, code in enumerate(first_code_data):
            if code not in save_plate_code:
                platename = plate_data_all.iloc[index,1]
                platepop = plate_data_all.iloc[index, 2]
                obj = {'ZSCode': code, 'ZSName': platename, 'TCExplain': '', 'StockList': [], 'num': 0, 'ZSPop': platepop}
                firstData.append(obj)

        data[current_time] = firstData
        # 写入文件
        try:
            with open(jsonfileaddr, 'w') as f:
                json.dump(data, f)
        except (FileNotFoundError, json.JSONDecodeError) as e:
            print(f"Error reading JSON file: {e}")




def initPageDate(win):
    '''
    设置初始化页面数据
    :param window:
    :return:
    '''
    print('-----初始化页面数据')
    #时间控件初始化
    win.dateEdit.setDate(QDate.currentDate())
    win.dateEdit.setMaximumDate(QDate.currentDate())
    win.dateEdit.dateChanged.connect(win.onDateChanged)
    win.comboBox.setCurrentIndex(2)
    win.comboBox_2.setCurrentIndex(3)
    if openstatus <= 0:
        win.tabWidget.setCurrentIndex(2)
    elif openstatus == 2:
        win.tabWidget.setCurrentIndex(0)
    elif openstatus == 3:
        win.tabWidget.setCurrentIndex(6)
    else:
        win.tabWidget.setCurrentIndex(1)

    # 获取数据源
    plate_data_all = kplAPI.getPlateData()
    win.show_table_public(win.tableWidget_pzbkrq, plate_data_all)
    # 获取第一行数据
    firstRowItem = win.tableWidget_pzbkrq.item(0, 0)
    if firstRowItem is None:
        return
    plateID = firstRowItem.text()
    win.plateID = plateID
    num = win.lineEdit.text()
    plate_data_Sub_all, _ = kplAPI.getPlateSubData(num, plateID)
    win.show_table_public(win.tableWidget_pzbkxgg, plate_data_Sub_all)

    #保存板块人气
    win.save_plate_rq(plate_data_all)
    #显示头部文件
    win.showTableHeadData()

    #早盘竞价涨
    win.showTableZpjjzData()

def initPageDateArfer(win):
    '''初始化数据后置，需要等待所有都启动后才启动'''
    print('----初始化数据后置，需要等待所有都启动后才启动----')
    # 加载板块轮动数据
    win.displayPlateRotation(None)
    #每日复盘
    win.dayReplay({})

    win.dayexpect()

    #市场情绪，需要等每日复盘启动完成
    win.showLineChart()

def bkds_function(param):
    '''
    执行定时获取板块数据
    :param param:
    :return:
    '''
    print('定时任务执行',datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    param.getBkDataOrShow()

def bkggds_function1(param):
    '''
    执行定时获取板块下个股数据
    :param param:
    :return:
    '''
    print('定时任务执行1',datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    param.getBkSubDataOrShow()


def bkld_function():
    '''执行板块轮动定时任务'''
    print('----执行板块轮动定时------')
    #{2023-12-29:[value]}
    request_dataAll = kplAPI.getLimitUpData()
    if request_dataAll is None:
        return
    jsonfileaddr = pathlib.Path(__file__).parent.resolve().as_posix() +'/'+ Gv.jsonfileaddr
    #读取文件
    data = {}
    try:
        with open(jsonfileaddr, 'r') as f:
            data = json.load(f)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(f"Error reading JSON file: {e}")
    global current_time
    dateStr = current_time
    requestData = data.get(dateStr)
    if requestData is None:
        first_key = next(iter(request_dataAll))
        oldData = data.get(first_key)
        if oldData is not None:
            current_time = first_key
            return
        dateStr = first_key
        requestData = request_dataAll.get(dateStr)
    else:
        return
    if requestData is None or len(requestData)<=0:
        return
    current_time = dateStr
    data[dateStr] = requestData
    #写入文件
    try:
        with open(jsonfileaddr, 'w') as f:
            json.dump(data,f)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(f"Error reading JSON file: {e}")

def hread_function(param):
    '''执行头部定时'''
    print('执行头部定时')
    param.showTableHeadData()

def dayexpect_function(win):
    '''每日预期定时'''
    print('执行每日预期定时')
    de.set_dayexpect()
    win.dayexpect()


def hread_savedata_function():
    print('----定时将头部数据写入json文件：{}'.format(current_time))
    data = {}
    if hreaddata is None or len(hreaddata)<=0:
        return
    hreadfileaddr = pathlib.Path(__file__).parent.resolve().as_posix() + '/' + Gv.hreadfileaddr
    try:
        with open(hreadfileaddr, 'r') as f:
            data = json.load(f)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(f"Error reading JSON file: {e}")

    last_five_items =  data.get(current_time)
    if last_five_items is not None:
        return
    data[current_time] = hreaddata
    try:
        with open(hreadfileaddr, 'w') as f:
            json.dump(data, f)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(f"Error reading JSON file: {e}")

def hread_showdata_function():
    print('----将头部数据读入全局变量')
    data = {}
    hreadfileaddr = pathlib.Path(__file__).parent.resolve().as_posix() + '/' + Gv.hreadfileaddr
    try:
        with open(hreadfileaddr, 'r') as f:
            data = json.load(f)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        print(f"Error reading JSON file: {e}")
    if data is None:
        return
    global hreaddata
    if openstatus <= 0 and len(data.items())>1:
        last_five_items = list(reversed(data.items()))[:2]
    else:
        last_five_items = list(reversed(data.items()))[:1]

    for key,value in last_five_items:
            hreaddata = value
            continue

def schedulerHandler(win):
    #获取定时时长
    bkds = win.comboBox.currentText()
    bkggds = win.comboBox_2.currentText()
    current_date = datetime.now().date()
    # 执行定时任务的开始时间和结束时间
    start_time = datetime(current_date.year, current_date.month, current_date.day,9,15)
    end_time = datetime(current_date.year, current_date.month, current_date.day, 15,30)
    if win.checkBox_zdsx.isChecked():
        if bkds is not None and len(bkds):
            job = scheduler.add_job(bkds_function, 'interval'
                              ,seconds=int(bkds)
                              ,start_date=start_time.strftime('%Y-%m-%d %H:%M:%S')
                              ,end_date=end_time.strftime('%Y-%m-%d %H:%M:%S')
                              ,args=[win])
            jobMap[Gv.PZBK] = job.id
        if bkggds is not None and len(bkggds):
            job = scheduler.add_job(bkggds_function1,'interval'
                              ,seconds=int(bkggds)
                              ,start_date=start_time.strftime('%Y-%m-%d %H:%M:%S')
                              ,end_date=end_time.strftime('%Y-%m-%d %H:%M:%S')
                              ,args=[win])
            jobMap[Gv.PZBKXGG] = job.id
    #板块轮动定时
    # 如果当前时间已经过了15点5分，则立即执行任务
    if openstatus <= 0:
        bkld_function()
        platepop.bkld_function(win.lineEdit.text(),current_time)
        #dayexpect_function(win)
    else:
        scheduler.add_job(bkld_function, trigger='cron', hour=15, minute=5, second=6, coalesce=True)
        #头部定时
        scheduler.add_job(hread_function, 'interval'
                          , seconds=60
                          , start_date=start_time.strftime('%Y-%m-%d %H:%M:%S')
                          , end_date=end_time.strftime('%Y-%m-%d %H:%M:%S')
                          , args=[win])
        scheduler.add_job(dayexpect_function, trigger='cron', hour=9, minute=27, second=26, coalesce=True, args=[win])
    hread_showdata_function()
    # 开始调度器
    scheduler.start()

def schedulerArferHandler(win):
    '''定时任务后置'''
    if openstatus <= 0:
        hread_savedata_function()

def get_process_port(pid):
    connections = psutil.net_connections()
    for conn in connections:
        if conn.pid == pid and conn.status == 'LISTEN':
            return conn.laddr.port
    return None

def init():
    date_day = datetime.today().date()
    global openstatus
    # kp_date = lhb.getDate()
    # date_day_lhb = datetime.strptime(kp_date, '%Y-%m-%d').date()
    # #TODO
    # if date_day_lhb<date_day :
    #     print('关市-LHB时间')
    #     openstatus = 0
    # else:
    current_time_now = datetime.now()
    current_hour = current_time_now.hour
    current_minute = current_time_now.minute
    # 如果当前时间已经过了15点5分，则立即执行任务
    if (current_hour > 15 or (current_hour == 15 and current_minute >= 5)) or (
            current_hour < 9 or (current_hour == 9 and current_minute <= 15)):
        print('关市')
        openstatus = 0
    else:
        print('开市')
        openstatus = 1
        if (current_hour == 9 and (current_minute >= 15 or current_minute <= 30)):
            print('集合竞价')
            openstatus = 2
        if (current_hour == 9 and (current_minute >= 25 or current_minute <= 30)):
            print('集合竞价')
            openstatus = 3


def freezpointTios(isChecked,num):
    #冰点提示
    if num is None or num>1000 or not isChecked or openstatus<=0:
        return
    engine = pyttsx3.init()
    engine.say('当前上涨数进入冰点，请注意短线风险与机会！！！！')
    engine.runAndWait()

if __name__ == '__main__':
   app = QApplication([])
   window = MainUI()
   init()
   #执行定时任务
   schedulerHandler(window)
   initPageDate(window)
   schedulerArferHandler(window)
   initPageDateArfer(window)
   window.show()

   # 创建一个线程来启动HTTP服务器
   #window.thread = threading.Thread(target=page.common.HttpClientResp.create_httpServer, args=(port_global,))
   #window.thread.start()
   window.thread = httpResp.HttpAppThread()
   window.thread.new_request.connect(window.on_http_message_received)
   window.thread.start()

   # 创建 WebSocketApp 线程对象
   # 创建一个队列和一个线程来处理WebSocket通信
   window.threadwbmsg = xgbwebMsg.WebSocketAppThread()
   window.threadwbmsg.message_received.connect(window.on_message_received)
   window.threadwbmsg.start()
   screens = QApplication.screens()
   app.exec()


